﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XSTDZ.ERP.Application.DataContracts;
using XSTDZ.ERP.Application;
using XSTDZ.ERP.Infrastructure;
using XSTDZ.ERP.WebApp.Models;
using XSTDZ.ERP.Core.Extentions;
using XSTDZ.ERP.WebApp.Models.Ado;
using XSTDZ.ERP.Infrastructure.Authentication;

namespace XSTDZ.ERP.WebApp.Controllers
{
    //收付款账单管理
    public class ReceivablePayableController : Controller
    {
        private readonly IReceivablePayableService billServiceImpl = ServiceLocator.Instance.GetService<IReceivablePayableService>();	
        //
        // GET: /ReceivablePayable/
        RefeModel model = new RefeModel(); 
        public ActionResult Index()
        {
           var refeList = model.GetRefeByModuleName(RefeTypeOption.财务账单);
           ViewBag.BillType = model.GetDropDownListItemsByCode(refeList);
            return View();
        }
        #region 查看详细
        [NoAuthorizated("Detail")]
        public ActionResult Detail(Guid id)
        {
            GetBillType();
            ViewBag.BillId = id;
            //ViewBag.SFBillType = type;
            //ViewBag.ReveBillNone = type == "0" ? "" : "none";
            //ViewBag.PayBillNone = type == "0" ? "none" : "";
            ReceivablePayableRecordDto r = new ReceivablePayableRecordDto();
            r.ReceivedMoney = 0;
            r.ReceivedMoneyPft = 0;
            r.PaidMoney = 0;
            r.OmitMoney = 0;

            ViewBag.BillModel = billServiceImpl.GetReceivablePayableBill(id);//获得相应的单据数据

            return View(r);
        }
        #endregion
        #region 付款明细记录

        [NoAuthorizated("Edit")]
        public ActionResult Edit(Guid id, string type)
        {
            GetBillType();
            ViewBag.BillId = id;
            ViewBag.SFBillType = type;
            ViewBag.ReveBillNone = type == "0" ? "" : "none";
            ViewBag.PayBillNone = type == "0" ? "none" : "";
            ReceivablePayableRecordDto r = new ReceivablePayableRecordDto();
            r.ReceivedMoney = 0;
            r.ReceivedMoneyPft = 0;
            r.PaidMoney = 0;
            r.OmitMoney = 0;

            var model = billServiceImpl.GetReceivablePayableBill(id);//获得相应的单据数据
            ViewBag.BillModel = model;
           
            return View(r);
        }
        [HttpPost]
        [NoAuthorizated("Edit")]
        public ActionResult Edit(ReceivablePayableRecordDto itemDto)
        {
            if (ModelState.IsValid)
            {
                try
                {
                        itemDto.CreateID = UserModel.GetLoginUserId(this.HttpContext);
                        itemDto.CreateTime = DateTime.Now;
                        itemDto.InvoiceType = itemDto.CreateID;
                        this.billServiceImpl.AddReceivablePayableDetail(itemDto);
                    
                }
                catch (Exception ex)
                {
                    return Content("0");
                }
                return Content("9");
            }

            return Content("0");
        }

        [NoAuthorizated("Edits")]
        public ActionResult Edits(string ids, string type)
        {
            GetBillType();
            ViewBag.IDS = ids;
            ViewBag.BillId = Guid.Empty;
            ViewBag.SFBillType = type;
            ViewBag.ReveBillNone = type == "0" ? "" : "none";
            ViewBag.PayBillNone = type == "0" ? "none" : "";
            ReceivablePayableRecordDto r = new ReceivablePayableRecordDto();
            r.ReceivedMoney = 0;
            r.ReceivedMoneyPft = 0;
            r.PaidMoney = 0;
            r.OmitMoney = 0;

            var idlst = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            IList<Guid> idguid = new List<Guid>();
            idlst.Each(t => { idguid.Add(Guid.Parse(t)); });

            var model = new ReceivablePayableBillDto();
            var models = billServiceImpl.GetReceivablePayableBills(idguid);//获得相应的单据数据
            models.Each(t => {
                if (t.BillClassify)
                {
                    model.BillPayable += t.BillPayable;
                    model.BillPayPft += t.BillPayPft;
                    model.BillPay += t.BillPay;
                }
                else
                {
                    model.BillReceivable += t.BillReceivable;
                    model.BillReceivPft += t.BillReceivPft;
                    model.BillReceiv += t.BillReceiv;
                }
            });
            model.BillClassify = models.First().BillClassify;
            if (model.BillClassify)
            {
                ViewBag.AllUnPay = model.BillPayable - (model.BillPayPft.HasValue ? model.BillPayPft : 0) - (model.BillPay.HasValue ? model.BillPay : 0);
            }
            else
            {
                ViewBag.AllUnPay = model.BillReceivable - (model.BillReceivPft.HasValue ? model.BillReceivPft : 0) - (model.BillReceiv.HasValue ? model.BillReceiv : 0);
            }
            ViewBag.BillModel = model;

            return View(r);
        }
        [HttpPost]
        [NoAuthorizated("Edits")]
        public ActionResult Edits(ReceivablePayableRecordDto itemDto)
        {
            #region 获得ＩＤ集合

            var ids = this.Request.Form["HidIds"];
            var idlst = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            IList<Guid> idguid = new List<Guid>();
            idlst.Each(t => {
                if (t.Trim().Length > 0)
                {
                    idguid.Add(Guid.Parse(t));
                }
            });

            #endregion
            var totalPay = this.Request.Form["HidTotalPay"];
          
            decimal _totalPay;
            decimal.TryParse(totalPay, out _totalPay);
            if (_totalPay < 0)
            {
                return Content("-2");
            }
            if (this.Request.Form["SFBillType"] == "0")
            {
                if (_totalPay > (itemDto.ReceivedMoney + itemDto.ReceivedMoneyPft))
                {
                    return Content("-2");
                }
            }
            else
            {
                if (_totalPay > (itemDto.PaidMoney + itemDto.OmitMoney))
                {
                    return Content("-2");
                }
            }

            if (ModelState.IsValid)
            {
                try
                {
                    itemDto.CreateID = UserModel.GetLoginUserId(this.HttpContext);
                    itemDto.CreateTime = DateTime.Now;
                    itemDto.InvoiceType = itemDto.CreateID;
                    this.billServiceImpl.AddReceivablePayableDetail(idguid,itemDto);
                    return Content("9");
                }
                catch (Exception ex)
                {
                    return Content("0");
                }
              
            }

            return Content("0");
        }
        #endregion
        #region 删除收付款账单明细（假删除）
         [NoAuthorizated("Delete")]
        public ActionResult Delete(Guid billId, string ids)
        {

            if (ids.Trim().Length > 0)
            {
                string[] arrayIds = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var guidIds = new List<Guid>();
                arrayIds.Each(id => guidIds.Add(Guid.Parse(id)));
                billServiceImpl.ConvertReturnBillDeleteState(billId, guidIds);
                return Content("9");
            }
           

            return Content("0");
        }
        #endregion
        #region 获取收付款账单列表数据

        //暂时获取所有数据
         [NoAuthorizated("GetJsonOfBills")]
        public ActionResult GetJsonOfBills()
        {
            #region EF的查询，效率低下，故暂时放弃不用

            /*
            var context = this.HttpContext;
           // string orgCode = context.Request.Form["orgCode"];
            string sortCode = context.Request.Form["sortCode"];
            string typeCode = context.Request.Form["typeCode"];

            int recordCount = 0;
            var productBills = billServiceImpl.getReceivablePayableBills(out recordCount,1, 100);

            if (productBills != null && productBills .Count() != 0)
            {
                var refeList = new RefeModel().GetRefeByModuleName(RefeTypeOption.财务账单);
                


                var jsonResult = productBills.Select(u => { u.DeleteState = u.Deleted == 0 ? "正常" : "已删除";
                u.SettleState = u.IsSettle > 0 ? "已结算" : "未结算";
                u.BillClassifyName = u.BillClassify ? "付款" : "收款";
                u.BillTypeName = refeList.Where(t => t.RefeCode == u.BillType.ToString()).Select(m => m.RefeName).FirstOrDefault();
                         return u; 
                });
                var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
                target = "{\"Rows\":" + target + ",\"Total\":\"" + recordCount + "\"}";
                return Content(target);
            }
            
            return Content("");
            */
            #endregion
            return Content(new BLLQuery().GetReceivablePayableBills(this.HttpContext));
        }

        //暂进获得明细行数据
        [NoAuthorizated("GetJsonOfBillItems")]
        public ActionResult GetJsonOfBillItems(Guid billId)
        {
            #region EF的查询，效率低下，故暂时放弃不用
            /*
            var productBills = billServiceImpl.getReceivablePayableBillDetails(billId);

            if (productBills != null && productBills.Count() != 0)
            {
                var refeList = new RefeModel().GetRefeByModuleName(RefeTypeOption.财务账单);



                var jsonResult = productBills.Select(u =>
                {
                    u.DeleteState = u.Deleted == 0 ? "正常" : "已删除";
                    u.SettleState = u.IsSettle > 0 ? "已结算" : "未结算";
                  //  u.BillClassifyName = u.BillClassify ? "付款" : "收款";
                   // u.bi = refeList.Where(t => t.Id == u.InvoiceType).Select(m => m.RefeName).FirstOrDefault();
                    return u;
                });
                var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
                target = "{\"Rows\":" + target + ",\"Total\":\"" + productBills.Count() + "\"}";
                return Content(target);
            }

            return Content("");
            */
            #endregion
            return Content(new BLLQuery().GetReceivablePayableBillDetails(billId));
        }
      
        #endregion
        #region private
        private void GetBillType()
        {
            var refeList = model.GetRefeByModuleName(RefeTypeOption.票据方式);
            ViewBag.PJBillType = model.GetDropDownListItemsById(refeList);

            var zfrefeList = model.GetRefeByModuleName(RefeTypeOption.支付方式);
            ViewBag.ZFBillType = model.GetDropDownListItemsById(zfrefeList);
        }
        #endregion
        #region 深圳财务
         public ActionResult SZIndex()
        {
           var refeList = model.GetRefeByModuleName(RefeTypeOption.财务账单);
           ViewBag.BillType = model.GetDropDownListItemsByCode(refeList);
            return View();
        }
        #endregion


        #region 期初账务
        //期初账务列表
         //深圳
         [NoAuthorizated("InitFinalIndexSZ")]
         public ActionResult InitFinalIndexSZ()
         {
             ViewBag.orgCode = SystemConfig.ShengZhenCode;
             return View("InitFinalIndex");
         }
        //成都
        [NoAuthorizated("InitFinalIndexCD")]
         public ActionResult InitFinalIndexCD()
         {
             ViewBag.orgCode = SystemConfig.ChengDuCode;
             return View("InitFinalIndex");
         }
        //通用
         [NoAuthorizated("InitFinalIndex")]
         public ActionResult InitFinalIndex()
         {
             return View();
         }
         public ActionResult InitFinal(Guid? billId, string orgCode)
         {
             var bill = new ReceivablePayableBillDto();
              var initSysData = DataInit.GetOrgAndDefaultWareHourse(SystemConfig.ChengDuCode);//初始化默认组织机构和仓库
                var org = initSysData.Keys.FirstOrDefault();
                bill.OrgID = org.Id;
                ViewBag.orgCode = orgCode;
             return View(bill);
         }
         [HttpPost]
         [NoAuthorizated("InitFinal")]
         public ActionResult InitFinal(ReceivablePayableBillDto billDto)
         {

             var orgCode = this.HttpContext.Request.Form["HidOrgCode"];
             IOrgService orgServiceImpl = ServiceLocator.Instance.GetService<IOrgService>();
             billDto.OrgID = orgServiceImpl.GetOrg(orgCode).Id;
             ViewBag.orgCode = orgCode;

             billDto.BillClassify = ((HttpContext.Request.Form["BillClassify"] ?? "0").ToString() == "1");
             if (billDto.ClientID.Equals(Guid.Empty))
             {
                 ModelState.AddModelError("ClientID", "客户不能为空");
                 return View(billDto);
             }
             if (billDto.BillClassify)//付
             {
                 if (billDto.BillPayable <= 0)
                 {
                     ModelState.AddModelError("BillPayable", "应付款不能小于0!");
                     return View(billDto);
                 }
             }
             else
             {

                 if (billDto.BillReceivable <= 0)
                 {
                     ModelState.AddModelError("BillReceivable", "应收款不能小于0!");
                     return View(billDto);
                 }

             }
             try
             {
                
                 billDto.CreateID = UserModel.GetLoginUserId(this.HttpContext);
                 billDto.BillType = -1;
                 this.billServiceImpl.AddReceivablePayable(billDto);
                 ViewBag.PostState = 9;
             }
             catch (Exception)
             {
                 
                
             }
                 
         
             return View(billDto);
         }
         [NoAuthorizated("DeleteBill")]
         public ActionResult DeleteBill(Guid billId)
         {
             if (!billId.Equals(Guid.Empty))
             {
                bool isDelete= billServiceImpl.DeleteReceivablePayable(billId);
                if (!isDelete)
                {
                    return Content("-1");
                }
                 return Content("9");

             }
             return Content("0");
         }
        #endregion
    }
}
